import time
import requests
from DrissionPage import ChromiumPage as Chromium

def monitor_game_status():
    """监控游戏状态并调用后端接口进行投注"""
    # 初始化浏览器
    tab = Chromium().latest_tab
    bool = tab.get('https://star.hasdgm.com/games/pc28/3?oddsMapId=4&mode=chat')
    if not bool:
        print("页面加载失败")
        return

    # 初始化期号
    if not hasattr(monitor_game_status, 'last_period'):
        current_period = get_current_period(tab)
        if current_period:
            monitor_game_status.last_period = current_period
            print(f"[{time.strftime('%Y-%m-%d %H:%M:%S')}] 初始化期号：{current_period}")
    
    try:
        print("开始自动投注监控")
        while True:  # 主循环
            try:
                current_period = get_current_period(tab)
                if not current_period:
                    print("无法获取期号，等待30秒后重试")
                    time.sleep(5)
                    continue
                
                # 期号没变化，继续等待
                if current_period == monitor_game_status.last_period:
                    print(f"[{time.strftime('%Y-%m-%d %H:%M:%S')}] 等待开奖，当前期号：{current_period}")
                    time.sleep(5)
                    continue
                
                # 期号发生变化
                print(f"[{time.strftime('%Y-%m-%d %H:%M:%S')}] 新一期开始，期号从 {monitor_game_status.last_period} 变更为 {current_period}")
                monitor_game_status.last_period = current_period
                
                # 调用后端接口获取投注信息
                bet_info = get_bet_info_from_backend(current_period)
                if bet_info:
                    place_bet(tab, bet_info['amount'], bet_info['type'])
                
                # 本轮结束，等待30秒后继续主循环
                time.sleep(30)
                
            except Exception as e:
                print(f"[{time.strftime('%Y-%m-%d %H:%M:%S')}] 监控过程发生错误: {e}")
                time.sleep(30)
                
    except Exception as e:
        print(f"[{time.strftime('%Y-%m-%d %H:%M:%S')}] 程序发生错误: {e}")
    finally:
        tab.quit()

def get_current_period(tab):
    """获取当前期号"""
    try:
        period_element = tab.ele('xpath=//span[text()="期 开奖号码"]/preceding-sibling::span[1]')
        if period_element:
            current_period = period_element.text.strip()
            return current_period
        
        print("未找到期号元素")
        return None
    except Exception as e:
        print(f"[{time.strftime('%Y-%m-%d %H:%M:%S')}] 获取期号失败: {e}")
        return None

def get_bet_info_from_backend(current_period):
    """调用后端接口获取投注信息"""
    try:
        # 假设后端接口的 URL
        url = f'https://example.com/api/get_bet_info?current_period={current_period}'
        
        # 发送 GET 请求
        response = requests.get(url)
        
        # 检查响应状态码
        if response.status_code == 200:
            # 解析 JSON 响应
            bet_info = response.json()
            # {'amount': 100, 'type': '龙'}//假设返回结构
            return bet_info
        else:
            print(f"请求失败，状态码: {response.status_code}")
            return None
    except Exception as e:
        print(f"调用接口失败: {e}")
        return None
    
def place_bet(tab, amount, bet_type):
    """执行下注操作"""
    try:
        amount_input = tab.ele('.fakeInput')
        amount_input.input(bet_type + str(amount))
        time.sleep(3)
        confirm_button = tab.ele('text=发送')
        confirm_button.click()
        print(f"投注成功: {bet_type} {amount}")
        return True
    except Exception as e:
        print(f"[{time.strftime('%Y-%m-%d %H:%M:%S')}] 下注失败: {str(e)}")
        return False

if __name__ == '__main__':
    monitor_game_status()